/**
 * 库存盘点相关API接口
 * 
 * 使用说明：
 * 1. 引入axios实例
 * 2. 根据实际后端接口地址修改baseURL
 * 3. 在组件中导入需要的API方法
 */

import axios from 'axios'

// 创建axios实例
const request = axios.create({
  baseURL: '/api', // 根据实际情况修改
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 可以在这里添加token等认证信息
    // const token = localStorage.getItem('token')
    // if (token) {
    //   config.headers.Authorization = `Bearer ${token}`
    // }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    return Promise.reject(error)
  }
)

// ==================== 盘点单接口 ====================

/**
 * 查询盘点列表（新接口）
 * @param params 查询参数
 * @returns Promise
 */
export const queryInventoryList = (params: {
  'QueryDTO.PageIndex'?: number
  'QueryDTO.PageSize'?: number
  'QueryDTO.InventoryCode'?: string
  'QueryDTO.DataStatus'?: string
  'QueryDTO.InventoryStartDateTime'?: string
  'QueryDTO.InventoryEndDateTime'?: string
  'QueryDTO.CreateName'?: string
  'QueryDTO.WarehouseDeptId'?: number
  'QueryDTO.WarehouseId'?: number
  'QueryDTO.WarehouseName'?: string
  'QueryDTO.HandlerName'?: string
}) => {
  return request({
    url: 'http://localhost:5110/api/Inventory/QueryInventoryList',
    method: 'get',
    params
  })
}

/**
 * 获取盘点单列表
 * @param params 查询参数
 * @returns Promise
 */
export const getInventoryList = (params: {
  code?: string
  result?: string
  type?: string
  warehouse?: string
  page?: number
  pageSize?: number
}) => {
  return request({
    url: '/inventory/list',
    method: 'get',
    params
  })
}

/**
 * 获取盘点单详情（新接口）
 * @param inventoryCode 盘点单号
 * @returns Promise
 */
export const getInventoryDetail = (inventoryCode: string) => {
  return request({
    url: 'http://localhost:5110/api/Inventory/GetInventoryDetail',
    method: 'get',
    params: { InventoryCode: inventoryCode }
  })
}

/**
 * 获取系统自动编号
 * @returns Promise
 */
export const getInventoryCode = () => {
  return request({
    url: '/inventory/getCode',
    method: 'get'
  })
}

/**
 * 保存盘点单（草稿）
 * @param data 盘点单数据
 * @returns Promise
 */
export const saveInventoryDraft = (data: {
  code: string
  type: string
  startTime: string
  endTime: string
  warehouse: string
  operator?: string
  remark?: string
  items: any[]
  files?: string[]
}) => {
  return request({
    url: '/inventory/saveDraft',
    method: 'post',
    data
  })
}

/**
 * 保存盘点单（正式）
 * @param data 盘点单数据
 * @returns Promise
 */
export const saveInventory = (data: {
  code: string
  type: string
  startTime: string
  endTime: string
  warehouse: string
  operator?: string
  remark?: string
  items: any[]
  files?: string[]
}) => {
  return request({
    url: '/inventory/save',
    method: 'post',
    data
  })
}

/**
 * 保存库存盘点（三表同时新增）
 * @param data 盘点DTO数据
 * @returns Promise
 */
export const SaveInventory = (data: {
  inventoryDTO: {
    inventoryId: number
    inventoryCode: string
    warehouseId: number
    handlerrId: number
    inventoryDateTime: string
    inventoryEndTime: string
    inventoryContent: string
    inventoryQuantity: string
    surplusQuantity: string
    inventoryShortageQuantity: string
    surplusAmount: string
    inventoryLossAmount: string
    dataStatus: number
    detailsList: any[]
    attachmentList: any[]
    operatorName: string
  }
  command?: string
}) => {
  return request({
    url: 'http://localhost:5079/api/Inventory/SaveInventory',
    method: 'post',
    data
  })
}

/**
 * 更新盘点单
 * @param id 盘点单ID
 * @param data 更新数据
 * @returns Promise
 */
export const updateInventory = (id: string, data: any) => {
  return request({
    url: `/inventory/update/${id}`,
    method: 'put',
    data
  })
}

/**
 * 删除盘点单
 * @param id 盘点单ID
 * @returns Promise
 */
export const deleteInventory = (id: string) => {
  return request({
    url: `/inventory/delete/${id}`,
    method: 'delete'
  })
}

/**
 * 批量删除盘点单
 * @param ids 盘点单ID数组
 * @returns Promise
 */
export const batchDeleteInventory = (ids: string[]) => {
  return request({
    url: '/inventory/batchDelete',
    method: 'delete',
    data: { ids }
  })
}

/**
 * 作废盘点单
 * @param id 盘点单ID
 * @returns Promise
 */
export const invalidInventory = (id: string) => {
  return request({
    url: `/inventory/invalid/${id}`,
    method: 'put'
  })
}

/**
 * 锁定仓库
 * @param id 盘点单ID
 * @returns Promise
 */
export const lockWarehouse = (id: string) => {
  return request({
    url: `/inventory/lockWarehouse/${id}`,
    method: 'put'
  })
}

/**
 * 导出盘点单
 * @param params 查询参数
 * @returns Promise
 */
export const exportInventory = (params: any) => {
  return request({
    url: '/inventory/export',
    method: 'get',
    params,
    responseType: 'blob'
  })
}

// ==================== 货品相关接口 ====================

/**
 * 获取货品列表
 * @param params 查询参数
 * @returns Promise
 */
export const getProductList = (params: {
  warehouseId?: string
  keyword?: string
  page?: number
  pageSize?: number
}) => {
  return request({
    url: '/products/list',
    method: 'get',
    params
  })
}

/**
 * 查询货品列表（新接口）
 * @param params 查询参数
 * @returns Promise
 */
export const queryProduct = (params: {
  PageIndex?: number
  PageSize?: number
  ProductCode?: string
  ProductName?: string
  Unit?: string
  WarehouseId?: number
}) => {
  return request({
    url: 'http://localhost:5110/api/Product/QueryProduct',
    method: 'get',
    params
  })
}

/**
 * 获取货品单位列表
 * @returns Promise
 */
export const getProductUnitList = () => {
  return request({
    url: 'http://localhost:5110/api/Product/GetProductUnitList',
    method: 'get'
  })
}

/**
 * 根据仓库获取货品库存信息
 * @param warehouseId 仓库ID
 * @param productIds 货品ID数组
 * @returns Promise
 */
export const getProductStockByWarehouse = (warehouseId: string, productIds: string[]) => {
  return request({
    url: '/products/stock',
    method: 'post',
    data: {
      warehouseId,
      productIds
    }
  })
}

// ==================== 仓库相关接口 ====================

/**
 * 获取仓库列表
 * @param params 查询参数
 * @returns Promise
 */
export const getWarehouseList = (params?: {
  keyword?: string
  status?: string
  page?: number
  pageSize?: number
}) => {
  return request({
    url: '/warehouses/list',
    method: 'get',
    params
  })
}

/**
 * 查询仓库列表（新接口）
 * @returns Promise
 */
export const queryWarehouse = () => {
  return request({
    url: 'http://localhost:5110/api/Warehouse/QueryWarehouse',
    method: 'get'
  })
}

/**
 * 获取仓库详情
 * @param id 仓库ID
 * @returns Promise
 */
export const getWarehouseDetail = (id: string) => {
  return request({
    url: `/warehouses/detail/${id}`,
    method: 'get'
  })
}

/**
 * 获取仓库编号
 * @returns Promise
 */
export const getWarehouseCode = () => {
  return request({
    url: '/warehouses/getCode',
    method: 'get'
  })
}

/**
 * 保存仓库（草稿）
 * @param data 仓库数据
 * @returns Promise
 */
export const saveWarehouseDraft = (data: {
  code: string
  name: string
  capacity?: string
  department?: string
  manager?: string
  phone?: string
  address?: string
  sort?: string
  status: string
  locked: boolean
  remark?: string
  locations: any[]
}) => {
  return request({
    url: '/warehouses/saveDraft',
    method: 'post',
    data
  })
}

/**
 * 保存仓库
 * @param data 仓库数据
 * @returns Promise
 */
export const saveWarehouse = (data: {
  code: string
  name: string
  capacity?: string
  department?: string
  manager?: string
  phone?: string
  address?: string
  sort?: string
  status: string
  locked: boolean
  remark?: string
  locations: any[]
}) => {
  return request({
    url: '/warehouses/save',
    method: 'post',
    data
  })
}

/**
 * 更新仓库
 * @param id 仓库ID
 * @param data 更新数据
 * @returns Promise
 */
export const updateWarehouse = (id: string, data: any) => {
  return request({
    url: `/warehouses/update/${id}`,
    method: 'put',
    data
  })
}

/**
 * 删除仓库
 * @param id 仓库ID
 * @returns Promise
 */
export const deleteWarehouse = (id: string) => {
  return request({
    url: `/warehouses/delete/${id}`,
    method: 'delete'
  })
}

/**
 * 批量删除仓库
 * @param ids 仓库ID数组
 * @returns Promise
 */
export const batchDeleteWarehouse = (ids: string[]) => {
  return request({
    url: '/warehouses/batchDelete',
    method: 'delete',
    data: { ids }
  })
}

/**
 * 获取库位列表
 * @param warehouseId 仓库ID
 * @param params 查询参数
 * @returns Promise
 */
export const getLocationList = (warehouseId: string, params?: {
  page?: number
  pageSize?: number
}) => {
  return request({
    url: `/warehouses/${warehouseId}/locations`,
    method: 'get',
    params
  })
}

/**
 * 添加库位
 * @param warehouseId 仓库ID
 * @param data 库位数据
 * @returns Promise
 */
export const addLocation = (warehouseId: string, data: any) => {
  return request({
    url: `/warehouses/${warehouseId}/locations`,
    method: 'post',
    data
  })
}

/**
 * 更新库位
 * @param warehouseId 仓库ID
 * @param locationId 库位ID
 * @param data 更新数据
 * @returns Promise
 */
export const updateLocation = (warehouseId: string, locationId: string, data: any) => {
  return request({
    url: `/warehouses/${warehouseId}/locations/${locationId}`,
    method: 'put',
    data
  })
}

/**
 * 删除库位
 * @param warehouseId 仓库ID
 * @param locationId 库位ID
 * @returns Promise
 */
export const deleteLocation = (warehouseId: string, locationId: string) => {
  return request({
    url: `/warehouses/${warehouseId}/locations/${locationId}`,
    method: 'delete'
  })
}

// ==================== 用户相关接口 ====================

/**
 * 获取用户列表（经办人）
 * @returns Promise
 */
export const getUserList = () => {
  return request({
    url: '/users/list',
    method: 'get'
  })
}

/**
 * 获取部门级联数据
 * @param parentId 父级部门ID，默认为0表示根节点
 * @returns Promise
 */
export const getDeptCascader = (parentId: number = 0) => {
  return request({
    url: 'http://localhost:5110/api/WarehouseDept/GetDeptCascader',
    method: 'get',
    params: { parentId }
  })
}

/**
 * 根据部门ID获取经办人列表
 * @param warehouseDeptId 仓库部门ID
 * @returns Promise
 */
export const getHandlerInfoList = (warehouseDeptId: number) => {
  return request({
    url: 'http://localhost:5110/api/HandlerInfo/GetHandlerInfoList',
    method: 'get',
    params: { warehouseDeptId }
  })
}

// ==================== 文件上传接口 ====================

/**
 * 上传文件
 * @param file 文件对象
 * @returns Promise
 */
export const uploadFile = (file: File) => {
  const formData = new FormData()
  formData.append('file', file)
  
  return request({
    url: '/upload',
    method: 'post',
    data: formData,
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

/**
 * 删除文件
 * @param fileId 文件ID
 * @returns Promise
 */
export const deleteFile = (fileId: string) => {
  return request({
    url: `/upload/delete/${fileId}`,
    method: 'delete'
  })
}

// ==================== 库位管理接口 ====================

/**
 * 查询库位列表
 * @returns Promise
 */
export const queryStoragelocation = () => {
  return request({
    url: 'http://localhost:5110/api/Storagelocation/QueryStoragelocation',
    method: 'get'
  })
}

// ==================== 盘点类型接口 ====================

/**
 * 获取盘点类型列表
 * @returns Promise
 */
export const getInventoryTypeList = () => {
  return request({
    url: 'http://localhost:5110/api/InventoryType/GetInventoryTypeList',
    method: 'get'
  })
}

export default {
  // 盘点单
  queryInventoryList,
  getInventoryList,
  getInventoryDetail,
  getInventoryCode,
  saveInventoryDraft,
  saveInventory,
  SaveInventory,
  updateInventory,
  deleteInventory,
  batchDeleteInventory,
  invalidInventory,
  lockWarehouse,
  exportInventory,
  // 货品
  getProductList,
  queryProduct,
  getProductUnitList,
  getProductStockByWarehouse,
  // 仓库
  getWarehouseList,
  queryWarehouse,
  getWarehouseDetail,
  getWarehouseCode,
  saveWarehouseDraft,
  saveWarehouse,
  updateWarehouse,
  deleteWarehouse,
  batchDeleteWarehouse,
  getLocationList,
  addLocation,
  updateLocation,
  deleteLocation,
  // 用户
  getUserList,
  getDeptCascader,
  getHandlerInfoList,
  // 文件
  uploadFile,
  deleteFile,
  // 库位
  queryStoragelocation,
  // 盘点类型
  getInventoryTypeList
}

